//SSY活动，NTMKT确认ＫＡＭ的调整信息
public class SSYNTMKTConfirmKAMAdustmentController
{
     public String RecordId
     {
           get
           {
               return String.valueOf(System.currentPageReference().getParameters().get('id')).substring(0,15);  
           }
           set;
     }
     public CommonMethod getCommonMethod;
     public Activity_Information__c ActivityInfo{get;set;}
     public String KASelectedValue{get;set;}
     public List<SelectOption> KAList{get;set;}
     public List<ApproveDynamicColumnEntry> ETEntryList{get;set;}
     public List<String> ResourceETColumnList{get;set;}
     public List<String> ResourceCostTypeColumnList{get;set;}
     public Boolean IsCheckAll{get;set;}//全选 
     public map<string,Integer> totalKaOutletList;//ka的门店总数
     public map<string,string> StatusForKaList;//ka关态列表
     
     public SSYNTMKTConfirmKAMAdustmentController()
     {
         ActivityInfo=[select name,Serial_Number__c,Activity_Start_Date__c,Activity_End_Date__c,Activity_Notice__c 
                             from Activity_Information__c where id=:RecordId];
                             
         getCommonMethod=new CommonMethod();
         LoadKAOutletTotalAndStatus();
         KAList=getCommonMethod.ParticipatorKAList(RecordId,true);
         LoadList();
     }
     public PageReference QueryKAList()
     {
        // throw new CustomException (KASelectedValue);  
       LoadList();
         return null;
     }
     public void LoadKAOutletTotalAndStatus()
     {
          totalKaOutletList=new map<string,integer>();
          StatusForKaList=new map<string,string>();
         for(ParticipatorArea__c area: [select KA__c,KA_Status__c,Outlet_Sum_Total__c from ParticipatorArea__c where Activity_Name__c=:RecordId and  KA__c!=NULL])
         {
             if(totalKaOutletList.containsKey(area.KA__c))
             {
                 Integer num=totalKaOutletList.get(area.KA__c);
                 num+=Integer.valueOf(area.Outlet_Sum_Total__c);
                 totalKaOutletList.put(area.KA__c,num);
             }
             else
             {
                 Decimal num=area.Outlet_Sum_Total__c;
                 totalKaOutletList.put(area.KA__c,num.intValue());
             }
             StatusForKaList.put(area.KA__c,area.KA_Status__c);
         }
     }
     public void LoadList()
     {
         string sqlResourceStr='select sum( QuantityConvertCase__c) SumTotal, Participator_Detail_Outlet__r.Participator_Area__r.KA__c,'+
                                             ' Resource_Allocation__r.Product_Name__r.Name ResourceName '+
                                             ' from Resource_Allocation_Detail__c '+
                                             ' where Participator_Detail_Outlet__r.Participator_Area__r.KA__c!=NULL '+ 
                                             ' and ActivityId__c=\''+RecordId+'\'';
                                             
      string sqlCompetitionStr='select sum(Money__c) SumTotal,Participator_Detail_Outlet__r.Participator_Area__r.KA__c,'+
                                               ' Activity_Competition_Brand_Information__r.Competition_Cost_Type__c ResourceName'+
                                               ' from Activity_Competition_Brand_Detail__c'+ 
                                               ' where ActivityId__c=\''+RecordId+'\''+
                                               ' and Participator_Detail_Outlet__r.Participator_Area__r.KA__c!=NULL ' ;                                   
      
       if(KASelectedValue!='0' && KASelectedValue!=NULL)      
       {
            sqlResourceStr+=' and Participator_Detail_Outlet__r.Participator_Area__r.KA__c=\''+KASelectedValue+'\'';    
            sqlCompetitionStr+=' and Participator_Detail_Outlet__r.Participator_Area__r.KA__c=\''+KASelectedValue+'\'';
       }     
       sqlResourceStr+= ' GROUP BY Participator_Detail_Outlet__r.Participator_Area__r.KA__c,'+
                                             ' Resource_Allocation__r.Product_Name__r.Name'+
                                             ' order by Resource_Allocation__r.Product_Name__r.Name asc';
       sqlCompetitionStr+=' group by Participator_Detail_Outlet__r.Participator_Area__r.KA__c,'+
                                        ' Activity_Competition_Brand_Information__r.Competition_Cost_Type__c'+
                                        ' order by Activity_Competition_Brand_Information__r.Competition_Cost_Type__c asc';
                                        
       //   throw new CustomException(sqlResourceStr);                        
         Map<String,ApproveDynamicColumnEntry> mapList=new map<String,ApproveDynamicColumnEntry>();//资源列表
         ETEntryList=new List<ApproveDynamicColumnEntry>();
         List<AggregateResult> groupResourceList=Database.query(sqlResourceStr);
         
                                                                                    
         ResourceETColumnList=getCommonMethod.GetDynamicETColumnList(groupResourceList);//获取列
         for(AggregateResult rs:groupResourceList)      
         {
             Decimal num=(Decimal)rs.get('SumTotal');
             if(!mapList.containsKey((String)rs.get('KA__c')))
             {
                 ApproveDynamicColumnEntry entry=new ApproveDynamicColumnEntry();
                 entry.IsCheck=false;
                 if(StatusForKaList.get((String)rs.get('KA__c'))=='KAM己提交')
                     entry.ApproveStatus='待审批';
                 else if(StatusForKaList.get((String)rs.get('KA__c'))=='' || StatusForKaList.get((String)rs.get('KA__c'))==NULL)
                     entry.ApproveStatus='未提交';
                 else
                     entry.ApproveStatus=StatusForKaList.get((String)rs.get('KA__c'));
                     
                 entry.Name=(String)rs.get('KA__c');
                 entry.OutletTotalNumber=(Integer)totalKaOutletList.get((String)rs.get('KA__c'));
                 entry.ResourceNumber1=num.intValue();
                 
                entry.ResourceNumber2=-1;
                entry.ResourceNumber3=-1;
                entry.ResourceNumber4=-1;
                entry.ResourceNumber5=-1;
                
                entry.CostType1=-1;
                entry.CostType2=-1;
                entry.CostType3=-1;
                entry.CostType4=-1;
                entry.CostType5=-1;
                mapList.put((String)rs.get('KA__c'),entry);
             }
             else
             {
                 ApproveDynamicColumnEntry entry=mapList.get((String)rs.get('KA__c'));
                 if(entry.ResourceNumber2==-1)
                   {
                       entry.ResourceNumber2=num.intValue();
                   }
                  else  if(entry.ResourceNumber3==-1)
                  {
                       entry.ResourceNumber3=num.intValue();
                  }
                  else   if(entry.ResourceNumber4==-1)
                  {
                       entry.ResourceNumber4=num.intValue();
                  }
                  else if(entry.ResourceNumber5==-1)
                  {
                       entry.ResourceNumber5=num.intValue();
                  } 
                  
                  mapList.put((String)rs.get('KA__c'),entry);
             }
         }   
         
         List<AggregateResult> competitionList=DataBase.query(sqlCompetitionStr);
                                                                         
        ResourceCostTypeColumnList=getCommonMethod.GetDynamicETColumnList(competitionList);//获取竞品费用类型列
         for(AggregateResult rs:competitionList)   
         {
             Decimal num=(Decimal)rs.get('SumTotal');
             if(mapList.containsKey((String)rs.get('KA__c')))
             {
                  ApproveDynamicColumnEntry entry=mapList.get((String)rs.get('KA__c'));
                 if(entry.CostType1==-1)
                   {
                       entry.CostType1=num;
                   }
                  else  if(entry.CostType2==-1)
                  {
                       entry.CostType2=num;
                  }
                  else   if(entry.CostType3==-1)
                  {
                       entry.CostType3=num;
                  }
                  else if(entry.CostType4==-1)
                  {
                       entry.CostType4=num;
                  } 
                   else if(entry.CostType5==-1)
                  {
                       entry.CostType5=num;
                  } 
                  
                  mapList.put((String)rs.get('KA__c'),entry);
             }
         }
             ETEntryList=mapList.values();
     }
     public PageReference AgreeApproveAction()
     {
        ApproveKAList('已审批');
        boolean flag=true;
        for(ParticipatorArea__c area:[select KA__c, KA_Status__c from ParticipatorArea__c where Activity_Name__c=:RecordId])
        {
            if(area.KA_Status__c !='已审批')
            {
                flag=false;
            }
        }
        //发送邮件给SRTM
        if(flag)
        {
            String BodyString='Please check the Email,now is your turn to adjust the resource.Thank you!';
           String subject='活动调整,活动名称'+ActivityInfo.Name;//+ActivityInit.Name;
           EmailHander.SendMail(BodyString,getCommonMethod.getUserEmailAddress('SRTM',RecordId),subject,'',null);
        }
         return null;
     }
     public PageReference RejectResourceApprovalAction()
     {
         ApproveKAList('拒绝(教育工具分配不合理)');
         return null;
     }
     public PageReference RejectComptitionApprovalAction()
     {
         ApproveKAList('拒绝(竞品费用填写不合理)');
         return null;
     }
     
     public void ApproveKAList(string approvelStr)
     {
          List<string> kaList=new List<string>();
          string filter='';
         for(ApproveDynamicColumnEntry entry:ETEntryList)
         {
             if(entry.IsCheck)
             {
                 if(entry.ApproveStatus=='待审批')
                 {
                     if(filter!='')
                         filter+=' or ';
                    filter+=' Key_Account__c like \'%'+entry.name+'%\'';
                     kaList.add(entry.Name);
                     entry.ApproveStatus=approvelStr;
                     entry.IsCheck=false;
                 }
             }
         }
         if(kaList.size()>0)
         {
             List<ParticipatorArea__c> pAreaList=[select id,KA_Status__c from ParticipatorArea__c where Activity_Name__c=:RecordId and KA__c in:kaList];
             for(ParticipatorArea__c area:pAreaList)
             {
                 area.KA_Status__c=approvelStr;
             }
             update pAreaList;
             
             if(approvelStr=='拒绝(竞品费用填写不合理)' || approvelStr=='拒绝(竞品费用填写不合理)')
             {
                 List<string> emailList=new List<string>();
                 for(User u:Database.query('select Email from User where '+filter))
                 {
                    emailList.add(u.Email);
                 }
                  //发送邮件到总部
                     String BodyString='Please check the Email,you submitted the application has been rejected!';
                     String subject='活动调整,活动名称:'+ActivityInfo.Name;
                     EmailHander.SendMail(BodyString,emailList,subject,'',null);
             }
         }
     }
     public PageReference Cancel()
     {
         pageReference pr = new pageReference('/'+RecordId);     
          pr.setredirect(true);   
          return pr;
     }
}